package com.fanshuai.netty;

import com.fanshuai.frame.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
public class NettyWebsocketHandler extends SimpleChannelInboundHandler<Object> {
    private WebSocketServerHandshaker handShaker;
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        log.info("channel active, channel={}", ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.info("channel inactive, channel={}", ctx.channel());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.debug("receive msg: {}", msg);
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            handleWebsocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    private boolean handleStatic(ChannelHandlerContext ctx, String uri) {
        if (uri.endsWith(".htm") || uri.endsWith(".html")
                || uri.endsWith(".js") || uri.endsWith(".css")
                || uri.endsWith(".jpg") || uri.endsWith(".jpeg") || uri.endsWith(".png") || uri.endsWith(".webp")) {

            String basePath = "/static";
            String filename = basePath + uri;
            InputStream in = this.getClass().getResourceAsStream(filename);
            if (null != in) {
                try {
                    byte[] content = new byte[in.available()];
                    in.read(content);
                    ByteBuf byteBuf = Unpooled.copiedBuffer(content);
                    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
                    ctx.channel().writeAndFlush(response);
                } catch (Exception e) {
                    log.error("" + e);
                    sendHttpResponse(ctx, "404 not found");
                }
            }
            return true;
        }
        return false;
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
        if (!request.decoderResult().isSuccess()) {
            sendHttpResponse(ctx, "bad request");
            return;
        }

        String uri = request.uri();
        try {
            uri = URLDecoder.decode(uri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
        if (uri.isEmpty() || uri.charAt(0) != '/') {
            sendHttpResponse(ctx, "url error");
            return;
        }
        if (handleStatic(ctx, uri)) {
            return;
        }

        if (!"websocket".equals(request.headers().get("Upgrade"))) {
            sendHttpResponse(ctx, "unsupported");
            return;
        }

        WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory("ws://0.0.0.0:8081/chat2", null, false);
        handShaker = factory.newHandshaker(request);
        if (handShaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
            return;
        }

        //websocket握手
        handShaker.handshake(ctx.channel(), request);
    }

    private void sendHttpResponse(ChannelHandlerContext ctx, String msg) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.BAD_REQUEST,
                Unpooled.copiedBuffer(msg.getBytes(StandardCharsets.UTF_8)));

        ChannelFuture f = ctx.channel().writeAndFlush(response);
        if (response.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    private void handleWebsocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (frame instanceof CloseWebSocketFrame) {
            handShaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        if (!(frame instanceof TextWebSocketFrame)) {
            log.info("unsupported media types");
            throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
        }

        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        String msg = textFrame.text();

        try {
            Message message1 = mapper.readValue(msg, Message.class);
            String uid = message1.getUid();

            switch (message1.getType()) {
                case 1:
                    ChannelManager.addChannel(uid, ctx.channel());
                    groupSend(uid + "进入直播间");
                    break;
                case 2:
                    groupSend(uid + "退出直播间");
                    ChannelManager.delChannel(uid);
                    break;
                case 3:
                    String text = message1.getText();
                    groupSend(uid + ": " + text);
                    break;
            }
        } catch (Exception e) {
            log.error("" + e);
        }
    }

    private void groupSend(String text) {
        Map<String, Channel> channelMap = ChannelManager.getChannels();
        for (Channel channel: channelMap.values()) {
            channel.writeAndFlush(new TextWebSocketFrame(text));
        }
    }
}
